import React, { useReducer } from 'react';

export default function ReducerLearn() {
  const initialState = { name: 'useReducer', count: 321 };
  const stateFun = (state, action) => {
    console.log('state, action', state, action);
    switch (action.type) {
      case 'increment':
        return { ...state, count: state.count + 20 };
      case 'decrement':
        return { ...state, count: state.count - 10 };
      case 'anyNum':
        return { ...state, count: state.count + action.anyNum };
      default:
        throw new Error();
    }
  };
  const [learnState, stateDispatch] = useReducer(stateFun, initialState);

  return (
    <div>
      <h2>useReducer 的学习</h2>
      <p>{JSON.stringify(learnState)}</p>
      <button
        onClick={() => {
          stateDispatch({ type: 'increment' });
        }}
      >
        加 20
      </button>
      <button
        onClick={() => {
          stateDispatch({ type: 'decrement' });
        }}
      >
        减 10
      </button>
      <button
        onClick={() => {
          stateDispatch({
            type: 'anyNum',
            anyNum: 9.9
          });
        }}
      >
        加 任意数
      </button>
    </div>
  );
}
